<script setup>
import { ref, watch } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import { ElMessage } from 'element-plus'


// 工具栏配置
const quillToolbar = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ header: 1 }, { header: 2 }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ indent: '-1' }, { indent: '+1' }],
  [{ direction: 'rtl' }],
  [{ size: ['small', false, 'large', 'huge'] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  [{ font: [] }],
  [{ align: [] }],
  ['clean'],
  ['link', 'image', 'video']
]

// 响应式数据
const showEdit = ref(false)
const showView = ref(false)
const viewData = ref({})

// ✅ 修复：初始化时补全 id 和 status
const drafts = ref(
    JSON.parse(localStorage.getItem('drafts') || '[]').map(d => ({
      ...d,
      status: d.status || 'draft',
      id: d.id || Date.now() + Math.random() // ✅ 补全 id
    }))
)

// 编辑表单
const form = ref({
  title: '',
  content: '',
  time: '',
  author: '',
  file: null,
  fileName: '',
  type: 'park',
  department: '1'
})

// 监听 drafts 变化并持久化
watch(drafts, (val) => {
  localStorage.setItem('drafts', JSON.stringify(val))
}, { deep: true })

// 文件上传处理
function handleFileUpload(e) {
  const file = e.target.files[0]
  if (file) {
    form.value.file = file
    form.value.fileName = file.name
  }
}

// 打开编辑弹窗
function openEdit() {
  showEdit.value = true

  const now = new Date()
  const localTime = now.getFullYear() + '-' +
      String(now.getMonth() + 1).padStart(2, '0') + '-' +
      String(now.getDate()).padStart(2, '0') + 'T' +
      String(now.getHours()).padStart(2, '0') + ':' +
      String(now.getMinutes()).padStart(2, '0')

  form.value = {
    title: '',
    content: '',
    time: localTime,
    author: '',
    file: null,
    fileName: '',
    type: 'park',
    department: '1'
  }
}

// 关闭编辑弹窗
function closeEdit() {
  showEdit.value = false
}

// 类型切换时重置部门（可选）
function onTypeChange() {
  if (form.value.type === 'park') {
    form.value.department = '1'
  }
}

// 提交编辑（保存为草稿）
function submitEdit() {
  if (!form.value.title || !form.value.content.trim()) {
    ElMessage.warning('请填写标题和内容')
    return
  }

  // ✅ 保存草稿时也添加 id 和 status
  drafts.value.unshift({
    ...form.value,
    status: 'draft',
    id: Date.now() + Math.random() // ✅ 添加唯一 id
  })
  ElMessage.success('已保存为草稿')
  showEdit.value = false
}

// ✅ 发布草稿：关键修复
function publishDraft(idx) {
  const draft = drafts.value[idx]

  // ✅ 给草稿本身添加 id（用于详情页查找）
  draft.id = draft.id || Date.now()
  draft.status = 'published'

  // 构造同步到公告栏的数据
  const publishedNotice = {
    id: draft.id,
    title: draft.title,
    content: draft.content,
    date: draft.time.split('T')[0],
    type: draft.type,
    department: draft.department || '1',
    author: draft.author,
    fileName: draft.fileName
  }

  // 同步到公告栏数据源
  const announcements = JSON.parse(localStorage.getItem('announcements') || '[]')
  announcements.unshift(publishedNotice)
  localStorage.setItem('announcements', JSON.stringify(announcements))

  ElMessage.success('发布成功，已同步到公告栏！')
}

// 查看草稿
function viewDraft(item) {
  viewData.value = { ...item }
  showView.value = true
}

// 关闭查看弹窗
function closeView() {
  showView.value = false
}

// 图片上传处理（默认使用 base64）
function handleImageAdded(imageData, quillRef, addImage) {
  addImage('')
}
</script>

<template>
  <div class="draft-box-wrapper">
    <!-- 通知编辑栏头部 -->
    <div class="draft-header">
      <span class="draft-title">通知编辑栏</span>
      <button class="edit-btn" @click="openEdit">编辑</button>
    </div>

    <!-- 草稿表格 -->
    <table class="draft-table" v-if="drafts.length">
      <thead>
      <tr>
        <th style="width:40%">标题</th>
        <th style="width:20%">发布时间</th>
        <th style="width:20%">发布人</th>
        <th style="width:10%">状态</th>
        <th style="width:10%">操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, idx) in drafts" :key="idx">
        <td>
          <span class="draft-item-title" @click="viewDraft(item)">{{ item.title }}</span>
        </td>
        <td>{{ item.time }}</td>
        <td>{{ item.author }}</td>
        <td>
            <span class="draft-status" :class="item.status">
              {{ item.status === 'draft' ? '草稿' : '已发布' }}
            </span>
        </td>
        <td>
          <button
              v-if="item.status === 'draft'"
              class="publish-btn"
              @click="publishDraft(idx)"
          >
            发布
          </button>
        </td>
      </tr>
      </tbody>
    </table>
    <div v-else class="empty-tip">暂无草稿</div>

    <!-- 编辑弹窗 - 全屏覆盖 -->
    <div v-if="showEdit" class="modal-mask" @click="closeEdit">
      <div class="modal" @click.stop>
        <!-- 标题栏 -->
        <div class="modal-title">
          编辑通知
          <span class="modal-close" @click="closeEdit">×</span>
        </div>

        <!-- 可滚动内容区域 -->
        <div class="modal-content-scroll">
          <!-- 标题 -->
          <div class="modal-form">
            <label>标题：</label>
            <input v-model="form.title" class="modal-input" placeholder="请输入通知标题" />
          </div>

          <!-- 内容 - 富文本编辑器 -->
          <div class="modal-form">
            <label style="vertical-align: top;">内容：</label>
            <div class="quill-wrapper" style="flex: 1;">
              <QuillEditor
                  v-model:content="form.content"
                  content-type="html"
                  placeholder="请输入通知内容，支持加粗、斜体、列表、图片、链接等..."
                  :toolbar="quillToolbar"
                  theme="snow"
                  style="height: 400px;"
                  @image-added="handleImageAdded"
              />
            </div>
          </div>

          <!-- 发布时间 -->
          <div class="modal-form">
            <label>发布时间：</label>
            <input v-model="form.time" type="datetime-local" class="modal-input" />
          </div>

          <!-- 发布人 -->
          <div class="modal-form">
            <label>发布人：</label>
            <input v-model="form.author" class="modal-input" placeholder="请输入发布人" />
          </div>

          <!-- 通知类型 -->
          <div class="modal-form">
            <label>通知类型：</label>
            <select v-model="form.type" class="modal-select" @change="onTypeChange">
              <option value="park">园区通知</option>
              <option value="dept">部门通知</option>
            </select>
          </div>

          <!-- 所属部门（仅部门通知时显示） -->
          <div v-if="form.type === 'dept'" class="modal-form">
            <label>所属部门：</label>
            <select v-model="form.department" class="modal-select">
              <option v-for="n in 10" :key="n" :value="String(n)">部门{{ n }}</option>
            </select>
          </div>

          <!-- 附件 -->
          <div class="modal-form">
            <label>附件：</label>
            <input type="file" class="modal-input" @change="handleFileUpload" />
            <span v-if="form.fileName" class="file-name">{{ form.fileName }}</span>
          </div>
        </div>

        <!-- 固定底部按钮 -->
        <div class="modal-footer">
          <button class="modal-ok" @click="submitEdit">确定</button>
          <button class="modal-cancel" @click="closeEdit">取消</button>
        </div>
      </div>
    </div>

    <!-- 查看弹窗 -->
    <div v-if="showView" class="modal-mask" @click="closeView">
      <div class="modal" @click.stop>
        <div class="modal-title">
          通知详情
          <span class="modal-close" @click="closeView">×</span>
        </div>

        <div class="modal-content-scroll">
          <div class="modal-info"><b>标题：</b>{{ viewData.title }}</div>
          <div class="modal-info">
            <b>内容：</b>
            <div
                v-html="viewData.content"
                class="view-content"
                style="margin-left: 24px; margin-top: 8px; line-height: 1.6; color: #333;"
            ></div>
          </div>
          <div class="modal-info"><b>发布时间：</b>{{ viewData.time }}</div>
          <div class="modal-info"><b>发布人：</b>{{ viewData.author }}</div>
          <div class="modal-info">
            <b>通知类型：</b>
            {{ viewData.type === 'park' ? '园区通知' : '部门通知' }}
          </div>
          <div v-if="viewData.department && viewData.type === 'dept'" class="modal-info">
            <b>所属部门：</b>部门{{ viewData.department }}
          </div>
          <div v-if="viewData.fileName" class="modal-info"><b>附件：</b>{{ viewData.fileName }}</div>
        </div>

        <div class="modal-footer">
          <button class="modal-cancel" @click="closeView">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 原有样式保持不变 */
.file-name {
  margin-left: 12px;
  color: #409eff;
  font-size: 14px;
}

.draft-box-wrapper {
  max-width: 1600px;
  margin: 30px auto;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 16px 24px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.draft-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.draft-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.edit-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 6px 22px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.edit-btn:hover {
  background: #66b1ff;
}

.draft-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 12px;
}

.draft-table th,
.draft-table td {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 8px;
  text-align: left;
  font-size: 14px;
  color: #606266;
}

.draft-table th {
  background: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

.draft-item-title {
  color: #222;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.2s;
  text-decoration: underline;
}

.draft-item-title:hover {
  color: #409eff;
}

.draft-status {
  font-size: 15px;
  padding: 2px 12px;
  border-radius: 12px;
  background: #f5f7fa;
  color: #909399;
  font-weight: 500;
}

.draft-status.published {
  background: #eaf4ff;
  color: #409eff;
}

.publish-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 5px 18px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.publish-btn:hover {
  background: #66b1ff;
}

.empty-tip {
  color: #bbb;
  text-align: center;
  margin: 40px 0;
  font-size: 16px;
}

/* ========== 全屏弹窗样式 ========== */
.modal-mask {
  position: fixed;
  z-index: 9999;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
}

.modal {
  width: 100vw;
  height: 100vh;
  max-width: none;
  max-height: none;
  display: flex;
  flex-direction: column;
  box-shadow: none;
  border-radius: 0;
  overflow: hidden;
  background: #fff;
}

.modal-title {
  font-size: 1.5rem;
  font-weight: bold;
  padding: 20px 36px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #234d78 0%, #6c7986 100%);
  color: #fff;
}

.modal-close {
  font-size: 1.8rem;
  cursor: pointer;
  color: #fff;
}

.modal-content-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 16px 36px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: #f9f9fb;
}

.modal-form {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  font-size: 15px;
}

.modal-form label {
  min-width: 100px;
  text-align: right;
  color: #333;
  font-size: 15px;
  padding-top: 8px;
}

.modal-input,
.modal-select {
  flex: 1;
  max-width: 300px;
  font-size: 15px;
  padding: 7px 12px;
  border: 1px solid #d4d7de;
  border-radius: 4px;
  background-color: #fff;
  color: #333;
  outline: none;
}

.modal-select {
  cursor: pointer;
}

.modal-select:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.quill-wrapper {
  flex: 1;
  border: 1px solid #d4d7de;
  border-radius: 4px;
  overflow: hidden;
}

.modal-footer {
  padding: 16px 36px;
  display: flex;
  justify-content: flex-end;
  gap: 18px;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.08);
}

.modal-ok,
.modal-cancel {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 2px;
  padding: 7px 28px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.modal-cancel {
  background: #909399;
}

.modal-ok:hover {
  background: #66b1ff;
}

.modal-cancel:hover {
  background: #b1b1b1;
}
</style>
